﻿using System;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Relocation.Base;
using Relocation.Base.UI;
using Relocation.Com;
using Relocation.Data;

namespace Relocation
{
	public partial class RelocateWindow : BaseForm
	{
		public Relocatees Relocate
		{
			get;
			private set;
		}


		public RelocateWindow()
			: base()
		{
			Initialize();
		}

		public RelocateWindow(Session session)
			: base(session)
		{
			Initialize();
			this.Field_RelcoateCode.Text = session.Project.projectCode;
			this.FieldIsChanged = false;
		}

		private void Initialize()
		{
			InitializeComponent();
			ToolTip toolTip = new ToolTip();
			toolTip.SetToolTip(Button_Display, "查看协议");

			this.Field_RelcoateCode.Tag = new ControlTag(Relocatees.GetPropName(t => t.relocateCode), new ValidatorInfo(new ValidatorInfo.ValidatorHandler(this.RelocateCodeValidating)));
			this.Field_Head.Tag = new ControlTag(Relocatees.GetPropName(t => t.head), new ValidatorInfo(true));
			this.Field_Phone.Tag = new ControlTag(Relocatees.GetPropName(t => t.phone));
			this.Field_Structure.Tag = new ControlTag(Relocatees.GetPropName(t => t.structure));
			this.Field_HouseStructure.Tag = new ControlTag(Relocatees.GetPropName(t => t.houseStructure));
			this.Field_Area.Tag = new ControlTag(Relocatees.GetPropName(t => t.area));
			this.Field_Property.Tag = new ControlTag(Relocatees.GetPropName(t => t.property));
			this.Field_Codes.Tag = new ControlTag(Relocatees.GetPropName(t => t.codes));
			this.Field_Persons.Tag = new ControlTag(Relocatees.GetPropName(t => t.persons));
			this.Field_RemoveText.Tag = new ControlTag(Relocatees.GetPropName(t => t.removeDate));
			this.Field_Created.Tag = new ControlTag(Relocatees.GetPropName(t => t.created));
			this.Field_Updated.Tag = new ControlTag(Relocatees.GetPropName(t => t.updated));
			this.Field_Idcard.Tag = new ControlTag(Relocatees.GetPropName(t => t.idcard));
			this.Field_Remark.Tag = new ControlTag(Relocatees.GetPropName(t => t.remark));
			this.Field_PlacementType.Tag = new ControlTag(Relocatees.GetPropName(t => t.placementType));
			this.Field_Money.Tag = new ControlTag(Relocatees.GetPropName(t => t.money));
			this.Field_Payment.Tag = new ControlTag(Relocatees.GetPropName(t => t.payment));
			this.Field_HouseType.Tag = new ControlTag(Relocatees.GetPropName(t => t.houseType));
			this.Field_EnableText.Tag = new ControlTag(Relocatees.GetPropName(t => t.enableDate));
			this.Field_FileName.Tag = new ControlTag(Relocatees.GetPropName(t => t.fileName));
			this.Field_StatusFlag.Tag = new ControlTag(Relocatees.GetPropName(t => t.head));
			this.Field_Residence.Tag = new ControlTag(Relocatees.GetPropName(t => t.residence));
			this.Field_Residence_area.Tag = new ControlTag(Relocatees.GetPropName(t => t.residence_area));
			this.Field_Residence_address.Tag = new ControlTag(Relocatees.GetPropName(t => t.residence_address));
			this.Field_Shop.Tag = new ControlTag(Relocatees.GetPropName(t => t.shop));
			this.Field_Shop_area.Tag = new ControlTag(Relocatees.GetPropName(t => t.shop_area));
			this.Field_Shop_address.Tag = new ControlTag(Relocatees.GetPropName(t => t.shop_address));
			this.Field_Other.Tag = new ControlTag(Relocatees.GetPropName(t => t.other));
			this.Field_Other_area.Tag = new ControlTag(Relocatees.GetPropName(t => t.other_area));
			this.Field_Other_address.Tag = new ControlTag(Relocatees.GetPropName(t => t.other_address));
			this.Field_Prev_head.Tag = new ControlTag(Relocatees.GetPropName(t => t.prev_head));
			this.Field_Prev_idcard.Tag = new ControlTag(Relocatees.GetPropName(t => t.prev_idcard));
		}

		//formLoad权限控制
		private void Relocate_Load(object sender, EventArgs e)
		{
			try
			{
				if (Session.User != null && Session.User.role == Session.KEY_ROLE_OPERATOR)
					this.panel4.Visible = false;				
				this.SetFileButtons(this.Field_FileName.Text.Trim());
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error(ex.Message);
			}
		}

		/// <summary>
		/// 页面加载Relocatees对象
		/// </summary>
		public void SetValueToInput(Relocatees relocatees)
		{
			try
			{
				base.SetValueToInput(relocatees);				
				this.SetFileButtons(Field_FileName.Text.Trim());
				//0未安置1已安置2无需安置
				this.Field_StatusFlag.Checked = relocatees.statusFlag.ToInt() == 1;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error("操作失败！");
			}
		}

		public RelocateWindow(Session session, Relocatees relocate)
			: base(session)
		{
			Initialize();
			this.Relocate = relocate;
			SetValueToInput(relocate);
			this.FieldIsChanged = false;
		}

		public void LoadRelocate(Relocatees relocate)
		{
			try
			{
				this.Relocate = relocate;
				SetValueToInput(relocate);
				this.FieldIsChanged = false;
			} catch (Exception ex)
			{				
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		public void EndEdit()
		{
			try
			{
				TextBox textBox;
				foreach (Control control in this.FieldControls)
				{
					textBox = control as TextBox;
					if (textBox == null)
						control.Enabled = false;
					else
						textBox.ReadOnly = true;
				}
				SetFileButtonsEnable(false);
				this.SetFileButtons(this.Field_FileName.Text.Trim());
				this.Button_Save.Text = "修改";
				this.Btuuon_Cancel.Visible = false;
				this.FieldIsChanged = false;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		public void BeginEdit()
		{
			try
			{
				TextBox textBox;
				foreach (Control control in this.FieldControls)
				{
					textBox = control as TextBox;
					if (textBox == null)
						control.Enabled = true;
					else
						textBox.ReadOnly = false;
				}

				if (Field_PlacementType.Text.Trim() == "货币化补偿")
					this.Field_Payment.Enabled = true;

				SetFileButtonsEnable(true);
				SetFileButtons(this.Field_FileName.Text.Trim());


				this.Button_Save.Text = "保存";
				this.Btuuon_Cancel.Visible = true;
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}
		}

		private void SetFileButtons(string fileName)
		{
			bool hasFile = !string.IsNullOrEmpty(fileName);
			this.Button_Display.Visible = hasFile;
			this.Button_DelProtocol.Visible = hasFile;
			this.Button_ScanProtocol.Visible = !hasFile;
		}

		private void SetFileButtonsEnable(bool enable)
		{
			this.Button_Display.Enabled = enable;
			this.Button_DelProtocol.Enabled = enable;
			this.Button_ScanProtocol.Enabled = enable;
		}

		//修改和新增保存
		private void relocateSave_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.Button_Save.Text == "修改")
				{
					this.BeginEdit();
				} else
				{
					if (!this.ValidatorAllControls())
						return;

					bool isNew = this.Relocate == null;		//是否新增
					if (isNew)
					{
						this.Relocate = new Relocatees();
						this.Relocate.created = DateTime.Now;
						this.Relocate.Projects = Session.Project;
						this.Field_Created.Text = System.DateTime.Now.ToShortDateString();
						this.Field_Updated.Text = System.DateTime.Now.ToShortDateString();
					}
					this.GetValueFromInput(this.Relocate);
					this.Relocate.statusFlag = (Field_PlacementType.Text == "货币化补偿" || Field_PlacementType.Text.Trim() == "") ? 2 : (this.Field_StatusFlag.Checked ? 1 : 0);
					Session.DataModel.Save(this.Relocate);
					this.Session.GetMainTreeView().Refresh(this.Relocate, isNew ? EntityState.Added : EntityState.Modified);
					this.FieldIsChanged = false;
					if (this.Parent == null)
					{
						this.DialogResult = DialogResult.OK;
						this.Close();
					} else
					{
						this.EndEdit();
					}
				}
			} catch (Exception ex)
			{
				Log.Error(ex.GetInnerExceptionMessage());
				MyMessagebox.Error("操作失败！");
			}
		}

		//取消按钮
		private void relocateCancel_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.Parent != null)
				{
					this.GetErrorProvider().Clear();
					this.LoadRelocate(this.Relocate);
					this.EndEdit();
				} else
					this.Close();
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error(ex.Message);
			}
		}

		//查看协议
		private void display_Click(object sender, EventArgs e)
		{
			try
			{
				string filePath = Field_FileName.Text.Trim();
				if (!string.IsNullOrEmpty(filePath))
				{
					if (!System.IO.File.Exists(filePath))
					{
						MyMessagebox.Show("未找到协议文件，有可能被删除或转移！");
					}
					Process.Start(filePath);
					return;
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error(ex.Message);
			}
		}

		//扫描协议
		private void scanProtocol_Click(object sender, EventArgs e)
		{
			try
			{
				FileWindow fileWin = new FileWindow(Session);
				if (fileWin.ShowDialog() == DialogResult.OK)
				{
					this.Field_FileName.Text = fileWin.strPath;
					this.SetFileButtons(this.Field_FileName.Text);
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Show("没有连接上扫描仪！");
			}
		}

		//删除协议
		private void delProtocol_Click(object sender, EventArgs e)
		{
			try
			{
				string filePath = Field_FileName.Text.Trim();
				if (string.IsNullOrEmpty(filePath))
					return;
				if (MyMessagebox.Confirm("是否删除此协议？").IsYes())
				{
					if (System.IO.File.Exists(filePath))
						System.IO.File.Delete(filePath);
					this.Field_FileName.Text = string.Empty;
					this.SetFileButtons(string.Empty);
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error("删除失败！");
			}
		}

		// RelocateesWindow页面刷新
		public override void Refresh()
		{
			base.Refresh();

			try
			{
				Relocatees _Relocate = this.Relocate;
				if (_Relocate != null)
				{
					SetValueToInput(_Relocate);
					foreach (Control control in this.FieldControls)
					{
						control.Enabled = false;
					}
					this.SetFileButtons(this.Field_FileName.Text.Trim());
					this.Button_Save.Text = "修改";
					this.Btuuon_Cancel.Visible = false;
					this.FieldIsChanged = false;
				}
			} catch (Exception ex)
			{				
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
				throw;
			}

		}


		#region 验证事件

		//安置方式验证
		private void placementType_TextChanged(object sender, EventArgs e)
		{
			if (Field_PlacementType.Text.Trim() == "货币化补偿" || Field_PlacementType.Text.Trim() == "")
			{
				this.Field_Payment.Enabled = true;
				this.Field_StatusFlag.Enabled = false;
			} else
			{
				this.Field_Payment.Enabled = false;
				this.Field_StatusFlag.Enabled = true;
			}
			this.FieldIsChanged = false;
		}


		#endregion


		private ValidatorInfo.ValidatorResult RelocateCodeValidating(Control control)
		{
			control.Text = control.Text.Trim();
			if (string.IsNullOrEmpty(control.Text))
			{
				return new ValidatorInfo.ValidatorResult(false, "必须填写！");
			} else
			{
				bool result = !(this.Relocate == null ?
					this.Session.DataModel.Relocatees.Any(t => control.Text.Equals(t.relocateCode))
					:
					this.Session.DataModel.Relocatees.Any(t => control.Text.Equals(t.relocateCode) && !this.Relocate.relocateID.Equals(t.relocateID)));
				return new ValidatorInfo.ValidatorResult(result, result ? string.Empty : "拆迁户编号已存在！");
			}
		}
	}
}
